document.addEventListener("DOMContentLoaded", (event) => {
    console.log("DOM 完全加载和解析");
    const pageurl = new URL(window.location.href);
    const key = pageurl.searchParams.get("key");
    const downAPI = "https://customerservice.bilibili.com/x/custom/msg_svr/v1/video_sign?key=" + key;
    const frame = document.getElementById("LinkView");
    var jump = document.getElementById("jump");
    frame.setAttribute("src", downAPI);
    jump.setAttribute("href", downAPI);
    });
    
    function getDownload()
    {
        const name = new URL(window.location.href).searchParams.get("name");

        const MessageDOM = document.getElementById("message");
        const obj = JSON.parse(MessageDOM.value);
        const downloadURL = obj.data.key;
        var suffix = downloadURL.substring(downloadURL.lastIndexOf("."), downloadURL.lastIndexOf("?"));

        if(name != "" && name != null)
        {
            var downloadName = name + suffix;
            var sfilename = "<br>文件名：" + downloadName;

        } else {
            var downloadName = downloadURL.substring(downloadURL.lastIndexOf("upload/"), downloadURL.lastIndexOf(".")) + suffix;
            var sfilename = "";
        }

        document.getElementById("downUrlView").innerHTML = "下载链接:<br>" + downloadURL + sfilename + "<br><br>注意：下载链接有有效期限制，不建议直接分享上面的链接！<br>本页面会调取服务器自动刷新最新链接，文件下载请使用此页面进行哦";
        download(downloadURL, downloadName);
    
    }


    // 下载逻辑
 /**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {Promise} 
 */
function getBlob(url) {
  return new Promise(resolve => {
      const xhr = new XMLHttpRequest();

      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
          if (xhr.status === 200) {
              resolve(xhr.response);
          }
      };

      xhr.send();
  });
}

/**
* 保存
* @param  {Blob} blob     
* @param  {String} filename 想要保存的文件名称
*/
function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename);
  } else {
      const link = document.createElement('a');
      const body = document.querySelector('body');

      link.href = window.URL.createObjectURL(blob);
      link.download = filename;

      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      
      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
  }
}

/**
* 下载
* @param  {String} url 目标文件地址
* @param  {String} filename 想要保存的文件名称
*/
function download(url, filename) {
  getBlob(url).then(blob => {
      saveAs(blob, filename);
  });
}